import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shimo_app/pages/components/loading_button.dart';
import 'package:shimo_app/pages/components/number_input.dart';

import '../components/baseDialog.dart';
import '../components/durationDialog.dart';
import '../components/hint.dart';
import 'manual_mode_controller.dart';

import 'package:flutter/services.dart';

class ManualModeComponent extends StatelessWidget {
  final controller = Get.put(ManualModeController());
  final state = Get.find<ManualModeController>().state;

  @override
  Widget build(BuildContext context) {
    return Container(
      // width: 600,
      // height: 550
      margin: EdgeInsets.only(top: 5, left: 30, right: 0),
      child: GetBuilder<ManualModeController>(builder: (controller) {
        return Column(
          children: [
            Container(
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(color: Colors.black12),
              child: Row(
                children: [
                  //https://mirrors.tuna.tsinghua.edu.cn/dart-pub
                  SizedBox(
                    width: 390,
                  ),
                  Text("模组选择",
                      style:
                          TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                  SizedBox(
                    width: 40,
                  ),
                  Text("模组1",
                      style:
                          TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                  Switch(
                      value: controller.module1,
                      onChanged: controller.moduleSetting
                          ? null
                          : (val) {
                              controller.module1 = val;
                              controller.setModule();
                              controller.update();
                              showHint("切换成功", HintType.SUCCESS);
                            }),
                  SizedBox(
                    width: 40,
                  ),
                  Text("模组2",
                      style:
                          TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                  Switch(
                      value: !controller.module1,
                      onChanged: controller.moduleSetting
                          ? null
                          : (val) {
                              controller.module1 = !val;
                              controller.setModule();
                              controller.update();
                              showHint("切换成功", HintType.SUCCESS);
                            }),
                ],
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Container(
              height: 70,
              margin: EdgeInsets.only(right: 20),
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(color: Colors.black12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text("X轴",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      Container(
                        height: 50,
                        width: 120,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          // 添加输入格式化器来限制输入
                          inputFormatters: [
                            // 只允许输入数字和负号（如果需要负数）
                            FilteringTextInputFormatter.allow(
                                RegExp(r'^(-?\d*|-?\d*-)$')),
                          ],
                          onChanged: (value) {
                            try {
                              // 处理空字符串
                              if (value.isEmpty) {
                                controller.xMoveDistance = 0;
                                Future.microtask(() => controller.update());
                                return;
                              }
                              int? parsedValue;
                              // 检查负号位置
                              if (value.startsWith('-')) {
                                // 负号在开头：直接解析
                                parsedValue = int.parse(value);
                              } else if (value.endsWith('-')) {
                                // 负号在结尾：去掉结尾负号后解析，然后取负数
                                String numericPart =
                                    value.substring(0, value.length - 1);
                                if (numericPart.isEmpty) {
                                  parsedValue = 0; // 如果只有负号，设置为0
                                } else {
                                  parsedValue = -int.parse(numericPart);
                                }
                              } else {
                                // 没有负号：直接解析正数
                                parsedValue = int.parse(value);
                              }
                              // 设置数值范围限制（例如：-1 000 000 到 1 000 000）
                              // 你可以根据实际需求调整这些值
                              const int minDistance = 0;
                              const int maxDistance = 662;
                              if (parsedValue < minDistance) {
                                controller.xMoveDistance = minDistance; // 最小值限制
                              } else if (parsedValue > maxDistance) {
                                controller.xMoveDistance = maxDistance; // 最大值限制
                              } else {
                                controller.xMoveDistance =
                                    parsedValue; // 在范围内的值
                              }
                              //重建Widget来更新显示
                              Future.microtask(() => controller.update());
                            } catch (e) {
                              controller.xMoveDistance = 0;
                            }
                            controller.update();
                          },
                          // 确保显示的值来自controller，这样会显示修正后的值
                          controller: TextEditingController(
                              text: controller.xMoveDistance.toString())
                            ..selection = TextSelection.collapsed(
                                // 2. 设置光标位置
                                offset: controller.xMoveDistance
                                    .toString()
                                    .length // 3. 计算光标偏移量
                                ),
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入运行距离",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text("mm",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      executeButton("Home", "x轴回home", controller.xGoHome),
                      SizedBox(
                        width: 10,
                      ),
                      executeButton("执行", "执行x轴移动", controller.xMove),
                    ],
                  ),
                  Row(
                    children: [
                      Text("Y轴",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      Container(
                        width: 120,
                        height: 50,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          inputFormatters: [
                            FilteringTextInputFormatter.allow(
                                RegExp(r'^(-?\d*|-?\d*-)$')),
                          ],
                          onChanged: (value) {
                            try {
                              if (value.isEmpty) {
                                controller.yMoveDistance = 0;
                                Future.microtask(() => controller.update());
                                return;
                              }
                              int? parsedValue;
                              if (value.startsWith('-')) {
                                parsedValue = int.parse(value);
                              } else if (value.endsWith('-')) {
                                String numericPart =
                                    value.substring(0, value.length - 1);
                                if (numericPart.isEmpty) {
                                  parsedValue = 0;
                                } else {
                                  parsedValue = -int.parse(numericPart);
                                }
                              } else {
                                parsedValue = int.parse(value);
                              }
                              const int minDistance = 0;
                              const int maxDistance = 297 - 12;
                              if (parsedValue < minDistance) {
                                controller.yMoveDistance = minDistance;
                              } else if (parsedValue > maxDistance) {
                                controller.yMoveDistance = maxDistance;
                              } else {
                                controller.yMoveDistance = parsedValue;
                              }
                              Future.microtask(() => controller.update());
                            } catch (e) {
                              controller.yMoveDistance = 0;
                            }
                            controller.update();
                          },
                          // 确保显示的值来自controller，这样会显示修正后的值
                          controller: TextEditingController(
                              text: controller.yMoveDistance.toString())
                            ..selection = TextSelection.collapsed(
                                offset:
                                    controller.yMoveDistance.toString().length),
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入运行距离",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text("mm",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      executeButton("Home", "y轴回home", controller.yGoHome),
                      SizedBox(
                        width: 10,
                      ),
                      executeButton("执行", "执行y轴移动", controller.yMove),
                    ],
                  )
                ],
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Divider(
              height: 10,
              thickness: 2,
              color: Colors.black,
            ),
            SizedBox(
              height: 30,
            ),
            Container(
              height: 70,
              margin: EdgeInsets.only(right: 20),
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(color: Colors.black12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // Row(
                  //   children: [
                  //     Text("清洗",
                  //         style: TextStyle(
                  //             fontSize: 20, fontWeight: FontWeight.bold)),
                  //     SizedBox(
                  //       width: 20,
                  //     ),
                  //     DropdownButton(
                  //         value: controller.clearChannel,
                  //         items: controller.channelItems
                  //             .map((e) => DropdownMenuItem<String>(
                  //                   value: e,
                  //                   child: Text(e),
                  //                 ))
                  //             .toList(),
                  //         onChanged: (String? value) {
                  //           controller.clearChannel = value!;
                  //           controller.update();
                  //         }),
                  //     SizedBox(
                  //       width: 10,
                  //     ),
                  //     SizedBox(
                  //       width: 120,
                  //       height: 50,
                  //       child: TextField(
                  //         keyboardType: TextInputType.number,
                  //         maxLines: 1,
                  //         textAlign: TextAlign.center,
                  //         onChanged: (value) {
                  //           try {
                  //             controller.clearDosage = int.parse(value);
                  //           } catch (e) {
                  //             controller.clearDosage = 0;
                  //           }
                  //           controller.update();
                  //         },
                  //         style:
                  //             TextStyle(textBaseline: TextBaseline.alphabetic),
                  //         decoration: InputDecoration(
                  //           hintStyle: TextStyle(
                  //               color: Color.fromRGBO(153, 151, 151, 0.3),
                  //               fontSize: 20),
                  //           hintText: "输入清洗用量",
                  //           // border: OutlineInputBorder(),
                  //           alignLabelWithHint: true,
                  //           contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                  //         ),
                  //       ),
                  //     ),
                  //     SizedBox(
                  //       width: 10,
                  //     ),
                  //     Text("ml"),
                  //     SizedBox(
                  //       width: 20,
                  //     ),
                  //     executeButton("执行", "清洗管路", controller.clear)
                  //   ],
                  // ),
                  Row(
                    children: [
                      Text(
                        "位置测试",
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      DropdownButton(
                        items: controller.posxItems
                            .map((e) => DropdownMenuItem<String>(
                                  value: e,
                                  child: Text(e),
                                ))
                            .toList(),
                        value: controller.selectedPosx,
                        onChanged: (String? val) {
                          controller.selectedPosx = val!;
                          controller.update();
                        },
                        hint: Text("选择x轴位置"),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      DropdownButton(
                        hint: Text("选择y轴位置"),
                        items: controller.posyItems
                            .map((e) => DropdownMenuItem<String>(
                                  value: e,
                                  child: Text(e),
                                ))
                            .toList(),
                        value: controller.selectedPosy,
                        onChanged: (String? val) {
                          controller.selectedPosy = val!;
                          controller.update();
                        },
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      executeButton(
                          "执行", "执行位置", () => controller.armMoveTest()),
                    ],
                  ),
                  Row(
                    children: [
                      Text("加液",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      DropdownButton(
                        value: controller.addPos,
                        items: controller.samplePosItems
                            .map((e) => DropdownMenuItem<String>(
                                  value: e,
                                  child: Text(e),
                                ))
                            .toList(),
                        onChanged: (String? val) {
                          this.controller.addPos = val!;
                          controller.update();
                        },
                      ),
                      DropdownButton(
                          value: controller.addChannel,
                          items: controller.channelItems
                              .map((e) => DropdownMenuItem<String>(
                                    value: e,
                                    child: Text(e),
                                  ))
                              .toList(),
                          onChanged: (String? value) {
                            this.controller.addChannel = value!;
                            controller.update();
                          }),
                      SizedBox(
                        width: 10,
                      ),
                      SizedBox(
                        height: 50,
                        width: 120,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          inputFormatters: [
                            // 只允许输入数字
                            FilteringTextInputFormatter.allow(
                                RegExp(r'[-0-9]')),
                          ],
                          onChanged: (value) {
                            try {
                              int parsedValue = int.parse(value);
                              if (parsedValue > 55)
                                parsedValue = 55;
                              else if (parsedValue < 0) parsedValue = 0;
                              controller.addDosage = parsedValue;
                              //重建Widget来更新显示
                              Future.microtask(() => controller.update());
                            } catch (e) {
                              controller.addDosage = 0;
                            }
                            controller.update();
                          },
                          // 确保显示的值来自controller，这样会显示修正后的值
                          controller: TextEditingController(
                              text: controller.addDosage.toString())
                            ..selection = TextSelection.collapsed(
                                // 2. 设置光标位置
                                offset: controller.addDosage
                                    .toString()
                                    .length // 3. 计算光标偏移量
                                ),
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入加液用量",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text("ml",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 10,
                      ),
                      executeButton("执行", "加液操作", controller.add),
                    ],
                  )
                ],
              ),
            ),
            SizedBox(
              height: 20,
            ),
            Container(
              height: 70,
              margin: EdgeInsets.only(right: 20),
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(color: Colors.black12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text("超声定容",
                          //颜色暂时变灰
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                            color: Colors.grey, // 添加灰色
                          )),
                      SizedBox(
                        width: 20,
                      ),
                      DropdownButton(
                          style: TextStyle(
                            color: Colors.grey, // 添加灰色
                            fontSize: 20, fontWeight: FontWeight.bold,
                          ),
                          value: controller.defineVolumeChannel,
                          items: controller.channelItems
                              .map((e) => DropdownMenuItem<String>(
                                    value: e,
                                    child: Text(e),
                                  ))
                              .toList(),
                          onChanged: (String? value) {
                            controller.defineVolumeChannel = value!;
                            controller.update();
                          }),
                      SizedBox(
                        width: 10,
                      ),
                      SizedBox(
                        height: 50,
                        width: 120,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          inputFormatters: [
                            // 只允许输入数字
                            FilteringTextInputFormatter.allow(
                                RegExp(r'[-0-9]')),
                          ],
                          onChanged: (value) {
                            try {
                              int parsedValue = int.parse(value);
                              if (parsedValue > 58)
                                parsedValue = 58;
                              else if (parsedValue < 0) parsedValue = 0;
                              controller.defineVolumeDosage = parsedValue;
                              //重建Widget来更新显示
                              Future.microtask(() => controller.update());
                            } catch (e) {
                              controller.defineVolumeDosage = 0;
                            }
                            controller.update();
                          },
                          // 确保显示的值来自controller，这样会显示修正后的值
                          // controller: TextEditingController(
                          //     text: controller.defineVolumeDosage.toString())
                          //   ..selection = TextSelection.collapsed(
                          //       // 2. 设置光标位置
                          //       offset: controller.defineVolumeDosage
                          //           .toString()
                          //           .length // 3. 计算光标偏移量
                          //       ),
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入定容用量",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text("ml",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      ElevatedButton(
                          onPressed: null,
                          child: Text("执行",
                              style: TextStyle(
                                  fontSize: 15, fontWeight: FontWeight.bold))),
                      SizedBox(
                        width: 10,
                      ),
                      ElevatedButton(
                          onPressed: null,
                          child: Text("位置",
                              style: TextStyle(
                                  fontSize: 15, fontWeight: FontWeight.bold))),
                    ],
                  ),
                  // Row(
                  //   children: [
                  //     Text(
                  //       "切换阀控制",
                  //       style: TextStyle(
                  //           fontSize: 20, fontWeight: FontWeight.bold),
                  //     ),
                  //     SizedBox(
                  //       width: 20,
                  //     ),
                  //     DropdownButton(
                  //         value: controller.switchValveChannel,
                  //         items: controller.channelItems
                  //             .map((e) => DropdownMenuItem<String>(
                  //                   value: e,
                  //                   child: Text(e),
                  //                 ))
                  //             .toList(),
                  //         onChanged: (String? value) {
                  //           controller.switchValveChannel = value!;
                  //           controller.update();
                  //         }),
                  //     SizedBox(
                  //       width: 10,
                  //     ),
                  //     executeButton(
                  //         "切换", "切换阀通道测试", () => controller.switchValve())
                  //   ],
                  // ),
                  Row(
                    children: [
                      Text("抽液",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      SizedBox(
                          height: 50,
                          width: 120,
                          // child: NumberInput(onChange: (val) {
                          //   controller.absorbDosage = val.toInt();
                          // }),
                          child: TextField(
                            keyboardType: TextInputType.number,
                            maxLines: 1,
                            textAlign: TextAlign.center,
                            inputFormatters: [
                              // 只允许输入数字
                              FilteringTextInputFormatter.allow(
                                  RegExp(r'[0-9]')),
                            ],
                            onChanged: (value) {
                              try {
                                controller.absorbDosage = int.parse(value);
                              } catch (e) {
                                controller.absorbDosage = 0;
                              }
                              controller.update();
                            },
                          )),
                      SizedBox(
                        width: 10,
                      ),
                      Text("ml",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      DropdownButton(
                        style: TextStyle(
                          color: Colors.grey, // 添加灰色
                          fontSize: 20, fontWeight: FontWeight.bold,
                        ),
                        value: controller.absorbPos,
                        hint: Text("输入位置"),
                        items: controller.samplePosItems
                            .map((e) => DropdownMenuItem<String>(
                                  value: e,
                                  child: Text(e),
                                ))
                            .toList(),
                        onChanged: (String? val) {
                          this.controller.absorbPos = val!;
                          controller.update();
                        },
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      executeButton(
                        "执行",
                        "执行吸液",
                        // controller.absorbDosage == 0
                        //     ? null
                        //     : () {
                        //         return controller.absorbTest();
                        //       },
                        null,
                      ),
                    ],
                  )
                ],
              ),
            ),
            SizedBox(
              height: 20,
            ),
            Container(
              height: 70,
              margin: EdgeInsets.only(right: 20),
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(color: Colors.black12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      // executeButton("初始化", "执行初始化", () async {
                      //   return await controller.initializeAction();
                      // }),
                      executeButton("初始化", "执行初始化", () async {
                        return controller.initializeAction();
                      }),
                      SizedBox(
                        width: 10,
                      ),
                      ElevatedButton(onPressed: () {}, child: Text("复位")),
                      SizedBox(
                        width: 10,
                      ),
                      LoadingButton(
                          onPressed: () async {
                            final r =
                                await controller.deviceService.abortAction(0);
                            await 500.milliseconds.delay();
                            showHint("执行${r ? '成功' : '失败'}",
                                r ? HintType.SUCCESS : HintType.DANGER);
                          },
                          child: Text("停止")),
                    ],
                  ),
                ],
              ),
            ),

            SizedBox(
              height: 20,
            ),
            // Divider(
            //   height: 10,
            //   thickness: 2,
            //   color: Colors.black,
            // ),
            // SizedBox(
            //   height: 10,
            // ),
            // Row(
            //   mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            //   children: [
            //     ElevatedButton(onPressed: () {}, child: Text("模组1")),
            //     ElevatedButton(onPressed: () {}, child: Text("模组2"))
            //   ],
            // ),
            // SizedBox(
            //   height: 30,
            // ),
            Container(
              height: 70,
              margin: EdgeInsets.only(right: 20),
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(color: Colors.black12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text("摇匀",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      DropdownButton(
                          style: TextStyle(
                            color: Colors.grey, // 添加灰色
                            fontSize: 20, fontWeight: FontWeight.bold,
                          ),
                          value: controller.shakeSpeed,
                          items: controller.shakeSpeedItems
                              .map((e) => DropdownMenuItem<String>(
                                    value: e,
                                    child: Text(e),
                                  ))
                              .toList(),
                          onChanged: (String? value) {
                            print(value);
                            controller.shakeSpeed = value!;
                            controller.update();
                          }),
                      SizedBox(
                        width: 10,
                      ),
                      SizedBox(
                        height: 50,
                        width: 120,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          inputFormatters: [
                            // 只允许输入数字
                            FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
                          ],
                          onChanged: (value) {
                            try {
                              controller.shakeDuration = int.parse(value);
                            } catch (e) {
                              controller.shakeDuration = 0;
                            }
                            controller.update();
                          },
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入摇匀时间",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text("min",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      // executeButton("执行", "摇匀动作", controller.shake),
                      executeButton("执行", "摇匀动作", null),
                    ],
                  ),
                  Row(
                    children: [
                      Text("Z轴",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      SizedBox(
                        height: 50,
                        width: 120,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          // 添加输入格式化器来限制输入
                          inputFormatters: [
                            // 只允许输入数字和负号（如果需要负数）
                            FilteringTextInputFormatter.allow(
                                RegExp(r'[-0-9]')),
                          ],
                          onChanged: (value) {
                            try {
                              int parsedValue = int.parse(value);
                              if (parsedValue > 58)
                                parsedValue = 58;
                              else if (parsedValue < 0) parsedValue = 0;
                              controller.zMoveDistance = parsedValue;
                              //重建Widget来更新显示
                              Future.microtask(() => controller.update());
                              ;
                            } catch (e) {
                              controller.zMoveDistance = 0;
                            }
                            controller.update();
                          },
                          controller: TextEditingController(
                              text: controller.zMoveDistance.toString())
                            ..selection = TextSelection.collapsed(
                                // 2. 设置光标位置
                                offset: controller.zMoveDistance
                                    .toString()
                                    .length // 3. 计算光标偏移量
                                ),
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入运行距离",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text("mm",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      executeButton("Home", "z轴运动", controller.down),
                      SizedBox(
                        width: 10,
                      ),
                      executeButton("执行", "z轴运动", controller.lift)
                    ],
                  )
                ],
              ),
            ),
            SizedBox(
              height: 20,
            ),
            Container(
              height: 70,
              margin: EdgeInsets.only(right: 20),
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(color: Colors.black12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text("加热",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      SizedBox(
                        height: 50,
                        width: 100,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          inputFormatters: [
                            // 只允许输入数字
                            FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
                          ],
                          onChanged: (value) {
                            try {
                              controller.heatTemperature = int.parse(value);
                            } catch (e) {
                              controller.heatTemperature = 0;
                            }
                            controller.update();
                          },
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入温度",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      Text("℃",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        height: 50,
                        width: 100,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          inputFormatters: [
                            // 只允许输入数字
                            FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
                          ],
                          onChanged: (value) {
                            try {
                              controller.heatDuration = int.parse(value);
                            } catch (e) {
                              controller.heatDuration = 0;
                            }
                            controller.update();
                          },
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入时间",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      Text("min(升)",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        height: 50,
                        width: 100,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          inputFormatters: [
                            // 只允许输入数字
                            FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
                          ],
                          onChanged: (value) {
                            //todo:??
                          },
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入时间",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      Text("min(平)",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 10,
                      ),
                      ElevatedButton(
                          // onPressed: () async {
                          //   showDurationDialog(
                          //     "加热中",
                          //   );
                          //   await controller.heatOn();
                          //   Navigator.pop(context);
                          // },
                          onPressed: null,
                          child: Text("执行",
                              style: TextStyle(
                                  fontSize: 15, fontWeight: FontWeight.bold)))
                    ],
                  ),
                  Row(
                    children: [
                      Text("冷却",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      SizedBox(
                        height: 50,
                        width: 100,
                        child: TextField(
                          keyboardType: TextInputType.number,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          inputFormatters: [
                            // 只允许输入数字
                            FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
                          ],
                          onChanged: (value) {
                            try {
                              controller.coolingDuration = int.parse(value);
                            } catch (e) {
                              controller.coolingDuration = 0;
                            }
                            controller.update();
                          },
                          style:
                              TextStyle(textBaseline: TextBaseline.alphabetic),
                          decoration: InputDecoration(
                            hintStyle: TextStyle(
                                color: Color.fromRGBO(153, 151, 151, 0.3),
                                fontSize: 20),
                            hintText: "输入时间",
                            // border: OutlineInputBorder(),
                            alignLabelWithHint: true,
                            contentPadding: EdgeInsets.only(top: 0, bottom: 0),
                          ),
                        ),
                      ),
                      Text("min",
                          style: TextStyle(
                              color: Colors.grey, // 添加灰色
                              fontSize: 20,
                              fontWeight: FontWeight.bold)),
                      SizedBox(
                        width: 20,
                      ),
                      // executeButton("执行", "开始冷却", controller.cooling)
                      executeButton("执行", "开始冷却", null)
                    ],
                  ),
                ],
              ),
            )
          ],
        );
      }),
    );
    // return Container(
    //   width: 200,
    //   height: 200,
    //   child: Column(
    //     children: [
    //       IconButton(
    //           onPressed: () {
    //             _showManualDialog();
    //           },
    //           icon: Icon(
    //             Icons.pan_tool,
    //           )),
    //       Text(
    //         "手动控制",
    //         style: TextStyle(fontSize: 30),
    //       )
    //     ],
    //   ),
    // );
  }

  Widget executeButton(
      String name, String title, Future<bool> Function()? action) {
    return GetBuilder<ManualModeController>(builder: (controller) {
      return ElevatedButton(
        onPressed: controller.busConnected &&
                controller.busState == 1 &&
                action != null
            ? () async {
                showDurationDialog(
                  "执行$title",
                  child: LoadingButton(
                      onPressed: () async {
                        await controller.abort();
                        // Navigator.pop(Get.context!);
                      },
                      child: Text("停止")),
                );
                bool result = false;
                try {
                  result = await action();
                } catch (e) {}
                Navigator.pop(Get.context!);
                showHint("执行${result ? "成功" : "失败"}",
                    result ? HintType.SUCCESS : HintType.DANGER);
              }
            : null,
        child: Text(name,
            style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold)),
      );
    });
  }
}
